package com.app.utils.util.view.expression.bean;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

import com.app.utils.util.ViewSizeUtils;

/**
 * 自定义大小的的ImageSpan
 * Created by xuxinghai on 2016/8/9.
 */
public class MyImageSpan extends ImageSpan {

    private int width = 23;
    private int height = 23;

    public MyImageSpan(Context context, int arg1) {
        super(context, arg1);
        width = ViewSizeUtils.dp2px(context,width);
        height = ViewSizeUtils.dp2px(context,height);
    }

    public MyImageSpan(Context context,Bitmap bitmap){
        super(context,bitmap);
        width = ViewSizeUtils.dp2px(context,width);
        height = ViewSizeUtils.dp2px(context,height);
    }

    public int getSize(Paint paint, CharSequence text, int start, int end,
                       Paint.FontMetricsInt fm) {
        Drawable d = getDrawable();
        d.setBounds(0, 0, width, height);
        Rect rect = d.getBounds();
        if (fm != null) {
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            int fontHeight = fmPaint.bottom - fmPaint.top;
            int drHeight = rect.bottom - rect.top;

            int top = drHeight / 2 - fontHeight / 4;
            int bottom = drHeight / 2 + fontHeight / 4;

            fm.ascent = -bottom;
            fm.top = -bottom;
            fm.bottom = top;
            fm.descent = top;
        }
        return rect.right;
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {
        Drawable b = getDrawable();
        b.setBounds(0, 0, width, height);
        canvas.save();
        int transY;
        transY = ((bottom - top) - b.getBounds().bottom) / 2 + top - 3;
        canvas.translate(x, transY);
        b.draw(canvas);
        canvas.restore();
    }
}
